/**
 * User: Paulo Fournier
 * Date: 05-08-2013
 * Mobile detail carousel view
 */

Ext.define('Mobile-app.view.MobileDetail', {
    extend: 'Ext.Panel',
    alias: 'widget.mobiledetailpanel',

    requires: [
        'Ext.carousel.Carousel'
    ],

    config: {
        modal: true,
        centered: true,
        hideOnMaskTap: true,
        width: '80%',
        height: '90%',
        padding: '0 0 0 0',

        layout: {
            type: 'vbox',
            align: 'stretch'
        },

        items: [
            {
                itemId: 'mobile-carousel',
                xtype: 'carousel',
                cls: 'panel-letter',
                flex: 1,
                items: [
                        {
                            xtype: 'toolbar',
                            docked: 'bottom',

                            // Make the toolbar scrollable
                            scrollable: {
                                direction: 'horizontal',
                                indicators: false
                            },

                            // Add several items into the toolbar
                            items: [
                                 { xtype: 'spacer' },
                                {
                                    xtype: 'button',
                                    ui: 'plain',
                                    itemId: 'addPoi',
                                    iconMask: true,
                                    iconCls: 'star'
                                },
                                {
                                    xtype: 'button',
                                    ui: 'plain',
                                    itemId: 'whatsaround',
                                    iconMask: true,
                                    iconCls: 'search'
                                },
                                 { xtype: 'spacer' }
                            ]
                        },
                        {
                        xtype: 'panel',
                        scrollable: true,
                        padding: '10 10 10 10',
                        items: {
                            xtype: 'toolbar',
                            docked: 'top',
                            ui: 'light',
                            title: $.t('main.detailed information')
                        },

                        tpl: new Ext.XTemplate(
                            '<b>',$.t('main.alias'),':</b> {reference}<br>',
                            '<b>',$.t('main.licensePlate'),':</b> {carPlate}<br><br>',

                            '<b>',$.t('main.date'),':</b> {timestamp:this.dateFormat}<br>',
                            '<b>',$.t('main.local'),':</b> {local}<br>',
                            '<b>',$.t('main.position'),':</b> <a href="https://maps.google.pt/maps?q={latitude},{longitude}" target="_blank">{latitude:this.convertLatitude}, {longitude:this.convertLongitude}</a><br>',
                            '<b>Velocidade:</b> {speed} Km/h<br>',
                            '<b>Direcção:</b> ',
                            '<tpl if="speed &gt; 0">' +
                                '{route:this.routeFormat}',
                            '<tpl else>',
                            '-',
                            '</tpl>',

                            '<br>',
                            '<b>',$.t('main.odometer'),':</b> {odometer}Km<br><br>',

                            '<b>',$.t('main.temperature_plural'),'</b> (p/ zona)<b>:</b> ',
                            '<tpl for="loadTemperature">',
                                '{#}: {.:this.tempFormat}, ',
                            '</tpl>',
                            '<br><br>',

                            '<b>',$.t('main.consumption'),':</b> {fuelConsumption} L/100Km<br>',
                            '<b>',$.t('main.fuel level'),':</b> {fuelLevel}%<br>',
                            '<b>',$.t('main.toll ok'),':</b> {tollOk} €<br>',
                            '<b>',$.t('main.toll nok'),':</b> {tollNok} €',
                            {
                                /***
                                 * Will convert time to human readable value
                                 * @param timestamp
                                 * @returns {String}
                                 */
                                dateFormat: function (timestamp) {
                                    return Ext.Date.format(new Date(timestamp), 'd-m-Y | H:i');
                                },
                                /**
                                 * Will translate the angle in directions
                                 * @param heading The angle in degrees [0,360]
                                 * @return String The heading format
                                 */
                                routeFormat: function (heading) {
                                    //set default angle
                                    var aCourse = 'N';
                                    //check the passed angle and get the alias
                                    if (heading <= 22.5) aCourse = $.t('general.compass N');
                                    else if (heading <= 67.5) aCourse = $.t('general.compass NE');
                                    else if (heading <= 112.5) aCourse = $.t('general.compass E');
                                    else if (heading <= 157.5) aCourse = $.t('general.compass SE');
                                    else if (heading <= 202.5) aCourse = $.t('general.compass S');
                                    else if (heading <= 247.5) aCourse = $.t('general.compass SW');
                                    else if (heading <= 292.5) aCourse = $.t('general.compass W');
                                    else if (heading <= 337.5) aCourse = $.t('general.compass NW');
                                    else aCourse = $.t('general.compass N');
                                    //return formatted heading
                                    return heading + 'º (' + aCourse + ')';
                                },
                                /***
                                 * Will format the temperature value
                                 * @param temp
                                 * @returns {string}
                                 */
                                tempFormat: function (temp) {
                                    return typeof temp !== 'string' && temp > -100 ? temp + 'ºC' : '-';
                                },
                                /***
                                 * Will convert the latitude to human readable
                                 * @param lat The latitude
                                 * @returns {String} Coordinate in degrees
                                 */
                                convertLatitude: function (lat) {

                                    return this.convertCorToDec(lat, 'lat')
                                },
                                /***
                                 * Will convert the longitude to human readable
                                 * @param lng The longitude
                                 * @returns {String} Coordinate in degrees
                                 */
                                convertLongitude: function (lng) {

                                    return this.convertCorToDec(lng, 'lng')
                                },

                                /**
                                 * Will receive coordinates in decimal degrees and transform in (aº b' c'') format
                                 * @param coordinate The coordinate in decimal degrees
                                 * @param  axis One of [lat,lng]
                                 * @return String The formatted coordinate
                                 */
                                convertCorToDec: function (coordinate, axis) {
                                    //check if lat and lng are defined
                                    if (!coordinate) return '';
                                    //set some local vars
                                    var sCor, d, m, s;
                                    //calculate position (North, South, East or West)
                                    if (axis == 'lat') {
                                        if (coordinate < 0) {
                                            axis = 'S';
                                            coordinate = Math.abs(coordinate);
                                        } else {
                                            axis = 'N';
                                        }
                                    }
                                    else {
                                        if (coordinate < 0) {
                                            axis = 'W';
                                            coordinate = Math.abs(coordinate);
                                        } else {
                                            axis = 'E';
                                        }
                                    }
                                    //calculate the latitude degrees, minutes and seconds
                                    sCor = coordinate.toString().split('.');
                                    d = sCor[0];
                                    m = ((coordinate - d) * 60).toString().split('.');
                                    s = ((((coordinate - d) * 60) - m[0]) * 60);
                                    m = m[0];
                                    //set values
                                    d = parseInt(d);
                                    m = Math.round(m);
                                    s = Math.round(s);
                                    //format sting
                                    sCor = axis + " " + d + "º " + m + "' " + s + "''";

                                    //return string
                                    return sCor;
                                }
                            }

                        )
                    },
                    {
                        xtype: 'panel',
                        scrollable: true,
                        items: {
                            xtype: 'toolbar',
                            docked: 'top',
                            ui: 'light',
                            title: $.t('main.vehicle')
                        },
                        padding: '10 10 10 10',
                        tpl: new Ext.XTemplate(
                            '<b>',$.t('main.alias'),':</b> {reference}<br>',
                            '<b>',$.t('main.licensePlate'),':</b> {carPlate}<br><br>',

                            '<b>',$.t('main.brand'),':</b> {brand}<br>',
                            '<b>',$.t('main.model'),':</b> {model}<br><br>',

                            '<b>',$.t('main.id'),':</b> {id}<br>',
                            '<b>',$.t('main.serial number'),':</b> {serialNumber}<br>',
                            '<b>',$.t('main.firmware'),':</b> {firmware}<br><br>',

                            '<div>',
                                '<div style="display: table-cell; vertical-align: middle;"><b>', $.t('main.tag_plural'),' (', $.t('main.user').toLowerCase(),'):&nbsp;</b></div><div style="display: table-cell; vertical-align: middle; border: 0px solid rgb(204, 204, 204); height: 34px; overflow: hidden; position: relative; padding-bottom: 0px;">{tagUser:this.tagLoad}</div>',
                            '</div><div>',
                                '<div style="display: table-cell; vertical-align: middle;"><b>', $.t('main.tag_plural'),' (', $.t('main.group').toLowerCase(),'):&nbsp;</b></div><div style="display: table-cell; vertical-align: middle; border: 0px solid rgb(204, 204, 204); height: 34px; overflow: hidden; position: relative; padding-bottom: 0px;">{tagGroup:this.tagLoad}</div>',
                            '</div>',
                            {
                                /***
                                 * Will mount all tags
                                 * @param tags (joined by ';')
                                 * @returns {string} An html formatted object
                                 */
                                tagLoad: function (tags) {

                                    if (!tags || tags === ';' || tags === ' ') return '-';

                                    var rst = '';
                                    tags = tags.split(';');

                                    for (i in tags) {
                                        rst += '<div class="tag-container" style="height:22px; background-color:#D5FFD5; cursor:default;">' +
                                            '<div class="tag-text">' +
                                            '<span style="position:relative; top:-1px;">' + tags[i] + '</span>' +
                                            '</div>' +
                                            '</div>';
                                    }

                                    return rst;
                                }
                            }
                        )
                    },
                    {
                        xtype: 'panel',
                        scrollable: null,
                        layout: 'fit',
                        items: [{
                            xtype: 'toolbar',
                            docked: 'top',
                            ui: 'light',
                            title: $.t('main.event_plural')
                        },{
                            fullscreen: true,
                            xtype: 'list',
                            cls: 'panel-letter',
                            disableSelection: true,
                            itemTpl: new Ext.XTemplate(
                                '<table border=0 width="100%">' +
                                '<tr>' +
                                '<td width=30 align="center">{eid:this.eventIcon}' +
                                '</td>' +
                                '<td>',
                                '<b>Data:</b> {tmx:this.dateFormat}<br>',
                                '<b>Tipo:</b> {alias}<br>',
                                '<div style="background-color: #acd4f0; padding: 3px; margin: 5px;">{description}</div>',
                                '</td>' +
                                '</tr>' +
                                '<tr>' +
                                '</table>',
                                {
                                    /***
                                     * Will convert time to human readable value
                                     * @param timestamp
                                     * @returns {String}
                                     */
                                    dateFormat: function (timestamp) {
                                        return Ext.Date.format(new Date(timestamp), 'd-m-Y | H:i');
                                    },

                                    /***
                                     * Will return the event icon
                                     * @param eid The event type id
                                     * @returns {string} The event html DOM
                                     */
                                    eventIcon: function(eid){

                                        var events = Ext.app.events,
                                            shape = events.shape,
                                            levels = events.levels,
                                            cfg = events.config[eid];

                                        return "<span class='e-c'>" +
                                                "<div class='e " + levels[cfg.alarm]['css'] + " " + shape[cfg.idShape] + "'>" +
                                                "<div class='e-i' style='background-image:url(resources/images/events/icons/" + cfg.imageName + ");'>" +
                                                "</div>" +
                                                "</div>" +
                                                "</span>";
                                    }
                                }
                            ),

                            store: Ext.create('Ext.data.Store', {
                                model: 'Mobile-app.model.Event'
                            })

                        }]
                    },{
                        xtype: 'panel',
                        scrollable: null,
                        layout: 'fit',
                        items: [
                            {
                                xtype: 'toolbar',
                                docked: 'top',
                                ui: 'light',
                                title: $.t('main.map')
                            },
                            Ext.create('Ext.Map', {
                                mapOptions: {
                                    center: new google.maps.LatLng(38.524801, -8.891029),  //nearby Setúbal
                                    zoom: 12,
                                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                                    navigationControl: true,
                                    navigationControlOptions: {
                                        style: google.maps.NavigationControlStyle.DEFAULT
                                    }
                                }
                            })
                        ]
                    }
                ]
            }
        ],
        listeners: [
            {
                delegate: '#mobile-carousel',
                event: 'activeitemchange',
                fn: 'activeItemChange'
            },
            {
                delegate:'#addPoi',
                event:'tap',
                fn: 'showAddPanel'
            },
            {
                delegate:'#whatsaround',
                event:'tap',
                fn: 'whatsAround'
            }
        ]
    },

    /***
     * Will show the add POI panel based on the mobile position
     */
    showAddPanel:function(){

        var record = Ext.getCmp('mobileList').getSelection()[0];

        this.fireEvent('showAddPoiPanel', record);
    },

    /***
     * Fires when the activeItem configuration is changed by setActiveItem
     * @param carousel The Ext.Container instance.
     * @param value The new item being set
     * @param oldValue The existing item
     * @param eOpts The options object passed to Ext.util.Observable.addListener
     */
    activeItemChange: function(carousel, value, oldValue, eOpts){

        //check if the item active is the map
        if(value.down('map') instanceof Ext.Map){
            this.fireEvent('showMarker', value.down('map'));
        }
        else if(value.down('list')){
            this.fireEvent('loadEvents', value.down('list'));
        }
    },

    /***
     * Hide panel with animation
     * @param animation
     */
    hide: function (animation) {

        var me = this;

        //we fire this event so the controller can deselect all items immediately.
        me.fireEvent('hideanimationstart', me);

        //show the mask again
        me.callParent();
    },

    /***
     * Will trigger the "whatsAround" proccess
     */
    whatsAround: function(){
        this.fireEvent('whatsAround');
    }
});
